package cn.com.xj.plat.controller;

import cn.com.xj.plat.service.AliOssService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    AliOssService aliOssService;

    @ResponseBody
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public String uploadImg(@RequestParam(value = "file", required = false)MultipartFile multipartFile) {
        String fileType = "";
        try {
            String fileName = multipartFile.getOriginalFilename();
            fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
                    fileName.lastIndexOf(".") + 4);
            if (!fileType.toLowerCase().equals("jpg") && !fileType.toLowerCase().equals("png")) {
                return "请上传jpg,png格式的图片。";
            }
            String uploadFileName = String.valueOf(RandomUtils.nextLong());
            String path = aliOssService.uploadFileToOss(multipartFile.getInputStream(),uploadFileName,fileType);
            return path;
        } catch (Exception e) {
            return "-1";
        }
    }


}
